﻿Public Class frmPhone

    Public Property phone As PhoneNumber
    Private isAdding As Boolean


    Private Sub frmEmail_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown

        If IsNothing(phone) Then
            setupFormForAdd()
        Else
            setupFormForEdit()
        End If

    End Sub

    Private Sub lnkSaveAndClose_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkSaveAndClose.LinkClicked

        If Not areInputsValid() Then
            Return
        End If

        bindFormToPhone()

        If isAdding Then
            frmEditContact.contact.phoneList.Add(phone)
        End If

        frmEditContact.refreshPhones()
        clearAndCloseForm()

    End Sub

   


    Private Sub lnkCancel_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkCancel.LinkClicked
        clearAndCloseForm()
    End Sub

    
    Private Sub setupFormForAdd()
        ' Set mode to "add" just in case it was previously "edit"
        isAdding = True
        Me.phone = New PhoneNumber
        bindPhoneToForm()
    End Sub

    Private Sub setupFormForEdit()
        isAdding = False
        bindPhoneToForm()
    End Sub

    Private Sub bindPhoneToForm()

        txtAreaCode.Text = phone.areaCode
        txtPrefix.Text = phone.prefix
        txtLineNumber.Text = phone.lineNumber

    End Sub

    Private Sub bindFormToPhone()

        phone.areaCode = txtAreaCode.Text
        phone.prefix = txtPrefix.Text
        phone.lineNumber = txtLineNumber.Text

    End Sub

    Private Function areInputsValid() As Boolean

        Dim isValid As Boolean = True
        errProvider.Clear()
        If (String.IsNullOrWhiteSpace(txtAreaCode.Text)) Then
            errProvider.SetError(txtAreaCode, "Required field.")
            isValid = False
        End If

        If (String.IsNullOrWhiteSpace(txtPrefix.Text)) Then
            errProvider.SetError(txtPrefix, "Required Field.")
            isValid = False
        End If

        If (String.IsNullOrWhiteSpace(txtLineNumber.Text)) Then
            errProvider.SetError(txtLineNumber, "Required Field.")
            isValid = False
        End If

        Return isValid

    End Function

    Private Sub clearAndCloseForm()
        Me.phone = Nothing
        errProvider.Clear()
        Me.Hide()
    End Sub

    Private Sub lnkSaveAndAddAnother_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkSaveAndAddAnother.LinkClicked

        If Not areInputsValid() Then
            Return
        End If

        bindFormToPhone()

        If isAdding Then
            frmEditContact.contact.phoneList.Add(phone)
        End If
        setupFormForAdd()

    End Sub
End Class